package ch.poole.openinghoursfragment.templates;

import ch.poole.openinghoursfragment.ResourceTable;
import ch.poole.openinghoursfragment.Util;
import ch.poole.openinghoursfragment.ValueArrayAdapter;
import ch.poole.openinghoursfragment.ValueWithDescription;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.data.rdb.RdbStore;
import ohos.data.resultset.ResultSet;
import org.angmarch.views.NiceSpinner;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TemplateDialog extends AbilitySlice {
    private static final String DEBUG_TAG = "TemplateDialog";
    private static final String EXISTING_KEY = "existing";
    private static final String ID_KEY = "id";
    private static final String CURRENT_KEY = "current";
    private static final String KEY_KEY = "key";
    private static final String TAG = "templatedialog_fragment";
    private Context mContext;
    private static String sCurrent;
    private static ValueWithDescription sKey;
    private static boolean sExisting;
    private static int sId;
    private UpdateCursorListener mUpdateCursorListener;

    public TemplateDialog(Context context) {
        this.mContext = context;
    }

    /**
     * Create a new instance of the dialog
     *
     * @param current  the current opening hours string
     * @param key      the key current is for
     * @param existing true if this is not a new template
     * @param id       the rowid of the template in the database or -1 if not saved yet
     * @param context  context
     * @return a TemplateDialog instance
     */
    public static TemplateDialog newInstance(final String current, final ValueWithDescription key, final boolean existing, final int id, Context context) {
        TemplateDialog f = new TemplateDialog(context);
        sCurrent = current;
        sKey = key;
        sExisting = existing;
        sId = id;
        return f;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_template_item_ohos);
        RdbStore db = new TemplateDatabaseHelper(mContext).getDb();
        final Checkbox defaultCheck = (Checkbox) findComponentById(ResourceTable.Id_is_default);
        final TextField nameEdit = (TextField) findComponentById(ResourceTable.Id_template_name);
        final NiceSpinner keySpinner = (NiceSpinner) findComponentById(ResourceTable.Id_template_key);
        final NiceSpinner regionSpinner = (NiceSpinner) findComponentById(ResourceTable.Id_template_region);
        final TextField objectEdit = (TextField) findComponentById(ResourceTable.Id_template_object);
        final DirectionalLayout dlworb = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_worb);
        final Text cancleTv = (Text) findComponentById(ResourceTable.Id_cancel);
        final Text titleTv = (Text) findComponentById(ResourceTable.Id_title);
        final Text saveTv = (Text) findComponentById(ResourceTable.Id_save);
        final Text deleteTv = (Text) findComponentById(ResourceTable.Id_delete);
        dlworb.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminate();
            }
        });
        String template = null;
        String templateKey = sKey != null ? sKey.getValue() : null;
        String templateRegion = null;
        String templateObject = null;
        if (sExisting) {
            ResultSet cursor = db.querySql(TemplateDatabase.QUERY_BY_ROWID, new String[]{Integer.toString(sId)});
            if (cursor.goToFirstRow()) {
                boolean isDefault = cursor.getInt(cursor.getColumnIndexForName(TemplateDatabase.DEFAULT_FIELD)) == 1;
                defaultCheck.setChecked(isDefault);
                String name = cursor.getString(cursor.getColumnIndexForName(TemplateDatabase.NAME_FIELD));
                nameEdit.setText(name);
                template = cursor.getString(cursor.getColumnIndexForName(TemplateDatabase.TEMPLATE_FIELD));
                templateKey = cursor.getString(cursor.getColumnIndexForName(TemplateDatabase.KEY_FIELD));
                templateRegion = cursor.getString(cursor.getColumnIndexForName(TemplateDatabase.REGION_FIELD));
                templateObject = cursor.getString(cursor.getColumnIndexForName(TemplateDatabase.OBJECT_FIELD));
            }
            cursor.close();

            titleTv.setText(mContext.getString(ResourceTable.String_edit_template));
            deleteTv.setText(mContext.getString(ResourceTable.String_Delete1));
            deleteTv.setVisibility(Component.VISIBLE);
            deleteTv.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    Logger.getLogger("TemplateDialog").log(Level.WARNING, "==deleting template==" + sId + " ");
                    TemplateDatabase.delete(db, sId);
                    if (mUpdateCursorListener != null) {
                        mUpdateCursorListener.newCursor(db);
                    }
                    onBackPressed();
                }
            });
        } else {
            defaultCheck.setChecked(false);
            nameEdit.setText("");
            deleteTv.setVisibility(Component.INVISIBLE);
            titleTv.setText(mContext.getString(ResourceTable.String_save_template));
        }
        cancleTv.setText(mContext.getString(ResourceTable.String_spd_ohf_cancel_capitalize));
        cancleTv.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
        String[] strings = Util.getStrings(mContext.getResourceManager(), ResourceTable.Strarray_key_entries);
        keySpinner.attachDataSource(Arrays.asList(strings.clone()));
        keySpinner.setSelectedIndex(0);
        Util.setSpinnerInitialEntryValue(mContext.getResourceManager(), ResourceTable.Strarray_key_values, keySpinner, templateKey);
        String[] values = Util.getStrings(mContext.getResourceManager(), ResourceTable.Strarray_region_values);
        String[] entries = Util.getStrings(mContext.getResourceManager(), ResourceTable.Strarray_region_entries);
        Set<ValueWithDescription> regionsSet = new TreeSet<>((v1, v2) -> v1.getDescription().compareTo(v2.getDescription()));
        for (int i = 0; i < values.length; i++) {
            regionsSet.add(new ValueWithDescription(values[i], entries[i]));
        }
        List<ValueWithDescription> regions = new ArrayList<>(regionsSet);
        regions.add(0, new ValueWithDescription("", mContext.getString(ResourceTable.String_spd_ohf_any)));
        ValueArrayAdapter adapter = new ValueArrayAdapter(regions, mContext);
        regionSpinner.setAdapter(adapter);
        regionSpinner.setSelectedIndex(0);
        if (templateRegion != null) {
            for (int i = 0; i < regions.size(); i++) {
                if (templateRegion.equals(regions.get(i).getValue())) {
                    regionSpinner.setSelectedIndex(i);
                    break;
                }
            }
        }
        objectEdit.setText(templateObject == null ? "" : templateObject);
        final String finalTemplate = template;
        saveTv.setText(mContext.getString(ResourceTable.String_Save_capitalize));
        saveTv.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String[] strings = Util.getStrings(mContext.getResourceManager(), ResourceTable.Strarray_key_values);
                List<String> keyValues = Arrays.asList(strings);
                int spinnerPos = keySpinner.getSelectedIndex();
                final String spinnerKey = spinnerPos == 0 ? null : keyValues.get(spinnerPos);
                spinnerPos = regionSpinner.getSelectedIndex();
                final String spinnerRegion = spinnerPos == 0 ? null : regions.get(spinnerPos).getValue();
                final String object = objectEdit.length() == 0 ? null : objectEdit.getText().toString();

                if (!sExisting) {
                    TemplateDatabase.add(db, spinnerKey, nameEdit.getText().toString(), defaultCheck.isChecked(), sCurrent, spinnerRegion, object);
                    onBackPressed();
                } else {
                    if (!sCurrent.equals(finalTemplate)) {
                        PickerDialog pickerDialog = new PickerDialog(mContext);
                        pickerDialog.getTitleView().setText(mContext.getString(ResourceTable.String_update_template));
                        ((Text) pickerDialog.getBtnConfirm()).setText(mContext.getString(ResourceTable.String_Yes));
                        pickerDialog.getBtnConfirm().setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                TemplateDatabase.update(db, sId, spinnerKey, nameEdit.getText().toString(), defaultCheck.isChecked(), sCurrent, spinnerRegion, object);
                                if (mUpdateCursorListener != null) {
                                    mUpdateCursorListener.newCursor(db);
                                }
                                pickerDialog.hide();
                                onBackPressed();
                            }
                        });
                        ((Text) pickerDialog.getBtnCancel()).setText(mContext.getString(ResourceTable.String_No));
                        pickerDialog.getBtnCancel().setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                TemplateDatabase.update(db, sId, spinnerKey, nameEdit.getText().toString(), defaultCheck.isChecked(), finalTemplate, spinnerRegion,
                                        object);
                                if (mUpdateCursorListener != null) {
                                    mUpdateCursorListener.newCursor(db);
                                    pickerDialog.hide();
                                    onBackPressed();
                                }
                            }
                        });

                        pickerDialog.show();
                    } else {
                        TemplateDatabase.update(db, sId, spinnerKey, nameEdit.getText().toString(), defaultCheck.isChecked(), sCurrent, null, null);
                        if (mUpdateCursorListener != null) {
                            mUpdateCursorListener.newCursor(db);
                        }
                        onBackPressed();
                    }
                }
            }
        });

    }

    public void setmUpdateCursorListener(UpdateCursorListener mUpdateCursorListener) {
        this.mUpdateCursorListener = mUpdateCursorListener;
    }
}
